$(document).ready(function() {
	$(".campaigns-viewmore").parent("li").removeClass("clickable");
	$(".campaigns-viewmore").live('click', function(e) {
	  e.preventDefault();
	  $(this).parent().addClass("viewmore-loading");
	  if($(this).hasClass('disabled')) return false;
	  element = $(this);
	  var campaignLastID = $("."+element.attr('id')+">li").last().prev().attr("id"); //get the last ID of the li
	  if (campaignLastID === null || campaignLastID === undefined) return false; //exit function if the ID is null

	$.get(ajaxURL, {'id':campaignLastID, 'section':element.attr('id')}, function(data) {
	  var bulkHTML = "";
	  if(data.length) {
	    for (var i = 0; i < data.length; i++) {
	      bulkHTML += renderCampaign(data[i].id, data[i].img_url, data[i].title, data[i].desc, data[i].campaign_url, data[i].campaign_category, data[i].completed);
	    }
	    $(element).parent().before(bulkHTML).removeClass("viewmore-loading");
    
	    if (data.length < 10) {
	      $(element).parent().html('No more campaign!').removeClass("viewmore-loading");
	    }
	  } else {
	    $(element).parent().html('No more campaign!').removeClass("viewmore-loading");
	  }
	}, 'json');
	return false;
	});
});

function renderCampaign(id, cImg, cTitle, cDesc, cUrl, cCompleted) {
  if (id == "") return "ID not specified";
  outputHtml = '<li id="' + id + '">';
  outputHtml += '<div class="clearfix">';
  outputHtml += '<img src="' + cImg + '" alt="' + cTitle + '" class=\"icon\" />';
  outputHtml += '<p class=\"action\"><a title="' + cTitle + '" href="' + cUrl + '" class=\"box-bounty\">Details &raquo;</a></p>';
  outputHtml += '<h4 class="title">'
  outputHtml += '<a href="' + cUrl + '">' + cTitle + '</a>';
  if (cCompleted != "") {
    outputHtml += ' <span class="campaign-completed">';
    outputHtml += '<img src="/images/check.png" alt="Check"> Completed';
    outputHtml += '</span>';
  }
  outputHtml += '</h4>';
  outputHtml += '</div>';
  outputHtml += '</li>';
  return outputHtml;
}